from utils import DateUtil, MysqlConnectInstance
import os

def get_waiting_generate_log():
    conn = MysqlConnectInstance().get_connection()
    cursor = conn.cursor()
    sql = """
    select log.id log_id,
       log.key_str,
       log.from_value,
       log.to_value,
       log.rate_date,
       template.template_path,
       template.today_output_path,
       template.history_output_path,
       from_name.currency_code as from_code,
       from_name.currency_en   as from_name,
       from_name.currency_fr   as from_name_fr,
       to_name.currency_code   as to_code,
       to_name.currency_en     as to_name,
       to_name.currency_fr     as to_name_fr
from file_template_output template
         inner join exchange_data_log log on template.exchange_key = log.key_str
         inner join currency_code_name from_name on from_name.currency_code = log.from_currency
         inner join currency_code_name to_name on to_name.currency_code = log.to_currency
where log.has_generated = 0;
    """
    cursor.execute(sql)
    return cursor.fetchall()


def generate_files(rows):
    generate_count = 0
    update_ids = []
    for row in rows:
        # 写入文件
        log_id, key_str, from_value, to_value, rate_date, template_path, today_output_path, history_output_path, from_code, from_name, from_name_fr, to_code, to_name, to_name_fr= row

        # 读取模板内容
        with open(template_path, 'r', encoding='utf-8') as file:
            template = file.read()
            # 替换变量
            rate_date_str = DateUtil.format_date(rate_date)
        parameters = {
            'to_name': to_name,
            'to_name_fr': to_name_fr,
            'to_code': to_code,
            'from_name': from_name,
            'from_name_fr': from_name_fr,
            'from_code': from_code,
            'rate_date': rate_date_str,
            'from_value': str(from_value).rstrip('0').rstrip('.'),
            'to_value': str(to_value).rstrip('0').rstrip('.'),
            'today': '',
            'today_fr':'',
            'today_comma': ''
        }

        if DateUtil.get_current_date() == rate_date_str:
            parameters['today'] = 'Today'
            parameters['today_fr'] = "Aujourd'hui"
            parameters['today_comma'] = ','
            file_name = today_output_path.format(**parameters)
        else:
            parameters['today'] = ''
            parameters['today_comma'] = ''
            file_name = history_output_path.format(**parameters)

        directory = os.path.dirname(file_name)
        if not os.path.exists(directory):
            os.makedirs(directory)
        result = generate_text(template, **parameters)
        with open(file_name, 'w', encoding='utf-8') as file:
            file.write(result)

        generate_count = generate_count + 1
        if generate_count % 60 == 0:
            print(f"Generated file: {generate_count / len(rows) * 100:.1f} %")
    print(f'all done! {generate_count}')


def generate_text(template, **kwargs):
    return template.format(**kwargs)


def main():
    logs = get_waiting_generate_log()
    generate_files(logs)


if __name__ == '__main__':
    main()
